package com.cz.nongyetongv5.utils;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.os.Environment;
import android.util.Base64;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class ImageUtil {

    /**
     * 检测是否有存储卡
     *
     * @return
     */
    public static boolean hasStore() {

        // 判断SDCard是否存在
        String status = Environment.getExternalStorageState();
        return status.equals(Environment.MEDIA_MOUNTED);
    }

    /**
     * 根据文件获得字节
     *
     * @param file
     * @return
     * @throws IOException
     */
    public static byte[] getFileByte(File file) throws IOException {
        BufferedInputStream bis = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(file));
            int bytes = (int) file.length();
            byte[] buffer = new byte[bytes];
            int readBytes = bis.read(buffer);
            if (readBytes != buffer.length) {
                throw new IOException("Entire file not read");
            }
            return buffer;
        } finally {
            if (bis != null) {
                bis.close();
            }
        }

    }

    /**
     * 获得存储卡的路径
     *
     * @return
     */
    public static File getStoragePath() {
        File storeDirectory = null;
        if (hasStore()) {
            storeDirectory = Environment.getExternalStorageDirectory();
        }
        return storeDirectory;
    }

    /**
     * 获得当前应用的数据目录
     */
    public static File getThisAppDataFile() {

        File dir = new File(getStoragePath(), "nongyetong");

        if (dir.exists()) {

            return dir;
        } else {
            if (dir.mkdirs()) {
                return dir;
            } else {
                return null;
            }
        }

    }

    /**
     * 根据用户ID获得用户头像
     *
     * @param userId
     * @return
     */
    public static File getUserPhotoByUserId(final String userId) {

        File[] files = getUserPhotoDir().listFiles(new FilenameFilter() {

            @Override
            public boolean accept(File dir, String filename) {

                if (filename.equals(userId + ".jpg")) {

                    return true;
                }

                return false;
            }
        });

        if (files.length >= 1) {

            return files[0];
        }

        return null;

    }

    /**
     * 创建文件夹
     *
     * @param dir
     * @return
     */
    public static boolean makeDir(File dir) {

        if (!dir.exists()) {
            return dir.mkdirs();
        } else {
            return false;
        }

    }

    /**
     * 获得用户 头像
     *
     * @return
     */
    public static File getUserPhotoDir() {

        File userPhotoDir = new File(getThisAppDataFile(), "touxiang");

        if (!userPhotoDir.exists()) {
            makeDir(userPhotoDir);
        }

        return userPhotoDir;

    }

    // 根据路径获得图片并压缩，返回bitmap用于显示
    public static Bitmap getSmallBitmap(String filePath, int reqWidth,
                                        int reqHeight) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, reqWidth,
                reqHeight);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;

        return BitmapFactory.decodeFile(filePath, options);
    }

    /**
     * 压缩图片
     *
     * @param res
     * @param resId
     * @param reqWidth
     * @param reqHeight
     * @return
     */
    public static Bitmap decodeSampledBitmapFromResource(Resources res,
                                                         int resId, int reqWidth, int reqHeight) {
        // 第一次解析将inJustDecodeBounds设置为true，来获取图片大小
        final BitmapFactory.Options options = new BitmapFactory.Options();

        options.inJustDecodeBounds = true;

        BitmapFactory.decodeResource(res, resId, options);
        // 调用上面定义的方法计算inSampleSize值
        options.inSampleSize = calculateInSampleSize(options, reqWidth,
                reqHeight);
        // 使用获取到的inSampleSize值再次解析图片
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeResource(res, resId, options);
    }

    public static Bitmap decodeSampledBitmapFromResource(String res,
                                                         int reqWidth, int reqHeight) {
        // 第一次解析将inJustDecodeBounds设置为true，来获取图片大小
        final BitmapFactory.Options options = new BitmapFactory.Options();

        options.inJustDecodeBounds = true;

        BitmapFactory.decodeFile(res, options);
        // 调用上面定义的方法计算inSampleSize值
        options.inSampleSize = calculateInSampleSize(options, reqWidth,
                reqHeight);
        // 使用获取到的inSampleSize值再次解析图片
        options.inJustDecodeBounds = false;
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        return BitmapFactory.decodeFile(res, options);
    }

    public static Bitmap decodeSampledBitmapFromResource(byte[] res,
                                                         int reqWidth, int reqHeight) {
        // 第一次解析将inJustDecodeBounds设置为true，来获取图片大小
        final BitmapFactory.Options options = new BitmapFactory.Options();

        options.inJustDecodeBounds = true;

        BitmapFactory.decodeByteArray(res, 0, res.length, options);
        // 调用上面定义的方法计算inSampleSize值
        options.inSampleSize = calculateInSampleSize(options, reqWidth,
                reqHeight);
        // 使用获取到的inSampleSize值再次解析图片
        options.inJustDecodeBounds = false;

        return BitmapFactory.decodeByteArray(res, 0, res.length, options);
    }

    /**
     * 根据指定宽高计算压缩值
     *
     * @param options
     * @param reqWidth
     * @param reqHeight
     * @return
     */
    public static int calculateInSampleSize(BitmapFactory.Options options,
                                            int reqWidth, int reqHeight) {

        // 源图片的高度和宽度
        final int height = options.outHeight;
        final int width = options.outWidth;

        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            // 计算出实际宽高和目标宽高的比率
            final int heightRatio = Math.round((float) height
                    / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            // 选择宽和高中最小的比率作为inSampleSize的值，这样可以保证最终图片的宽和高
            // 一定都会大于等于目标的宽和高。
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }

        return inSampleSize;
    }

    /**
     * 将Bitmap转换为本地的文件
     *
     * @param savePhoto
     * @param src
     */
    public static void bigmapSave(File savePhoto, Bitmap src, int quality) {

        FileOutputStream fos = null;

        BufferedOutputStream bos = null;

        try {
            fos = new FileOutputStream(savePhoto);

            bos = new BufferedOutputStream(fos);

            src.compress(CompressFormat.JPEG, quality, bos);

            bos.flush();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bos != null) {
                    bos.close();
                }

                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    /**
     * 旋转图片
     */
    public static int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
        }
        return degree;
    }

    /**
     * 旋转图片
     *
     * @param angle  : 取值90 180 270
     * @param bitmap
     * @return
     */
    public static Bitmap rotaingImageView(int angle, Bitmap bitmap) {
        // 旋转图片 动作
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);

        // 创建新的图片
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
                bitmap.getWidth(), bitmap.getHeight(), matrix, true);

        return resizedBitmap;
    }

    /**
     * 将二进制文件转换为base64
     *
     * @param path
     * @return
     */
    public static String bitToFromFile(String path) {

        FileInputStream fis = null;

        String data = null;
        try {

            File file = new File(path);

            fis = new FileInputStream(file);

            byte[] buffer = new byte[(int) (file.length())];

            fis.read(buffer);

            data = Base64.encodeToString(buffer, 0, buffer.length,
                    Base64.DEFAULT);

        } catch (Exception e) {

        } finally {
            try {
                if (fis != null)
                    fis.close();
            } catch (IOException e) {
            }
        }

        return data;

    }

    public static String bitToBase64FromFile(String path) {

        FileInputStream fis = null;

        String data = null;
        try {

            File file = new File(path);

            fis = new FileInputStream(file);

            byte[] buffer = new byte[(int) (file.length())];

            fis.read(buffer);

            data = Base64.encodeToString(buffer, 0, buffer.length,
                    Base64.DEFAULT);

        } catch (Exception e) {

        } finally {
            try {
                if (fis != null)
                    fis.close();
            } catch (IOException e) {
            }
        }

        return data;

    }

    public static String getJsonByName(Context context, String name) {

        StringBuffer json = new StringBuffer();

        try {

            InputStream is = context.getAssets().open(
                    "json" + File.separator + name);

            InputStreamReader isr = new InputStreamReader(is);

            while (isr.ready()) {
                json.append((char) isr.read());
            }

            isr.close();

            is.close();

        } catch (IOException e) {

        }

        return json.length() < 1 ? null : json.toString();

    }

}
